<script setup lang="ts">
defineOptions({
  name: "FULLSCREEN_PREVIEW"
});

import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import { getToken } from "@/utils/auth";
import * as XLSX from "xlsx/xlsx.mjs";
import { renderAsync } from "docx-preview";

const router = useRoute();

const fileURL = ref();
const txtRef = ref();
const sheetList = ref<Array<any>>([]);
const loading = ref<boolean>(false);

const setResponseType = () => {
  const {
    query: { type = "" }
  } = router;
  if (["txt"].includes(type as string)) {
    return "";
  } else {
    return "arraybuffer";
  }
};

const getFile = () => {
  loading.value = true;
  const {
    query: { type = "", id = "", fileName = "", moduleName = "" }
  } = router;
  const params = {
    id: id //1343
    // fileName: fileName, //'202406271346221806202393046802432.xlsx' ,
    // moduleName: moduleName || ""
  };
  axios({
    method: "post",
    url: "/ifp/sharing/api/v1/file/download",
    data: params,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || ""
    },
    responseType: setResponseType()
  })
    .then(async res => {
      if (["txt"].includes(type as string)) {
        previewTxt(res.data);
      } else if (["xls", "xlsx"].includes(type as string)) {
        previewExcel(res.data);
      } else if (["docx"].includes(type as string)) {
        previewWorld(res.data);
      } else if (["mp4"].includes(type as string)) {
        previewVideo(res.data);
      } else if (["pdf", "png", "jpg", "jpeg"].includes(type as string)) {
        previewPDF(res.data);
      }
    })
    .catch(() => {
      loading.value = false;
    });
  loading.value = false;
};

// txt
const previewTxt = data => {
  txtRef.value.innerHTML = data;
};

// PDF
const previewPDF = data => {
  const blob = new Blob([data], {
    type: "application/pdf;chartset=UTF-8"
  });
  fileURL.value = URL.createObjectURL(blob);
};

// xlsx
const previewExcel = data => {
  let workbook = XLSX.read(data, { type: "binary" });
  let sheetFileList = workbook.SheetNames;
  sheetFileList.forEach((item, index) => {
    let ws = workbook.Sheets[item];
    let fileContent = "";
    try {
      // 把excel文件流转化为html字符串，以便于v-html使用
      fileContent = XLSX.utils.sheet_to_html(ws);
      sheetList.value.push({
        name: item,
        isSelected: index == 0,
        content: fileContent
      });
    } catch (err) {
      console.error(err);
    }
  });
};

// docx
const previewWorld = data => {
  renderAsync(data, txtRef.value);
};

// mp4
const previewVideo = data => {
  fileURL.value = URL.createObjectURL(new Blob([data]));
};

const init = () => {
  window.document.title = "文件预览";
};

onMounted(() => {
  init();
  getFile();
});
</script>

<template>
  <div v-loading="loading" class="preview-container">
    <div v-if="['txt', 'docx'].includes(router.query.type as string)" ref="txtRef" />
    <div v-else-if="['xlsx'].includes(router.query.type as string)">
      <div v-for="(item, index) in sheetList" v-show="item.isSelected" :key="index" class="excelTable" v-html="item.content" />
    </div>
    <div v-else-if="['png', 'jpg', 'jpeg'].includes(router.query.type as string)" ref="txtRef">
      <img :src="fileURL" />
    </div>
    <video v-else-if="['mp4'].includes(router.query.type as string)" autoplay controls :src="fileURL" />
    <iframe v-else width="100%" height="100%" name="FULLSCREEN_DOCUMENTMANAGE_PREVIEW" frameborder="0" :src="fileURL" />
  </div>
</template>

<style lang="scss" scoped>
.preview-container {
  width: 100%;
  height: 100%;
  margin: 0;
}
</style>
